package com.zhouyu.commonapi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.ErrorHandler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description:线程池设置
 *
 * @author zhouyu
 * @create 2020/9/14
 * @since 1.0.0
 */
@Configuration
public class ThreadPoolConfig {

    /** 核心线程数 */
    private static final int CORE_POOL_SIZE = 8;
    /** 最大先线程数 */
    private static final int MAX_POOL_SIZE = 15;

    /** 非核心线程存活时间 */
    private static final int KEEP_ALIVE_SECONDS = 10;
    /** 任务队列大小 */
    private static final int QUEUE_CAPACITY = 80;

    private static final String THREADNAME_PREFIX = "COMMON-THREAD-";

    /**
     * 常用线程池，@Async需要配置使用这个线程池
     */
    @Bean
    public static ThreadPoolTaskExecutor commonThreadPool() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        threadPoolTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        threadPoolTaskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        threadPoolTaskExecutor.setQueueCapacity(QUEUE_CAPACITY);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        threadPoolTaskExecutor.setThreadNamePrefix(THREADNAME_PREFIX);
        //线程池的优雅停止，必须等所有的线程完成后关闭
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        return threadPoolTaskExecutor;
    }
}
